﻿using LazyFieldDemo.Helpers;
using LazyFieldDemo.Models;
using LazyFieldDemo.ViewModels;
using Orchard.ContentManagement;
using Orchard.ContentManagement.Drivers;
using Orchard.Data;

namespace LazyFieldDemo.Drivers {
    public class CustomerPartDriver : ContentPartDriver<CustomerPart> {
        private readonly IContentManager _contentManager;
        private readonly IRepository<Country> _countryRepository;

        public CustomerPartDriver(IContentManager contentManager, IRepository<Country> countryRepository) {
            _contentManager = contentManager;
            _countryRepository = countryRepository;
        }

        protected override string Prefix {
            get { return "Customer"; }
        }

        protected override DriverResult Display(CustomerPart part, string displayType, dynamic shapeHelper) {
            return Combined(
                ContentShape("Parts_Customer", () => shapeHelper.Parts_Customer(
                    ShippingAddress: _contentManager.BuildDisplay(part.ShippingAddress, displayType),
                    BillingAddress: _contentManager.BuildDisplay(part.BillingAddress, displayType))),
                ContentShape("Parts_Customer_SummaryAdmin", () => shapeHelper.Parts_Customer_SummaryAdmin(
                    ShippingAddress: _contentManager.BuildDisplay(part.ShippingAddress, displayType),
                    BillingAddress: _contentManager.BuildDisplay(part.BillingAddress, displayType)))
            );
        }

        protected override DriverResult Editor(CustomerPart part, dynamic shapeHelper) {
            var viewModel = new CustomerViewModel {
                FirstName = part.FirstName,
                LastName = part.LastName,
                ShippingAddress = AddressViewModel.Map(part.ShippingAddress),
                BillingAddress = AddressViewModel.Map(part.BillingAddress),
            };
            return ContentShape("Parts_Customer_Edit", () => shapeHelper.EditorTemplate(TemplateName: "Parts/Customer", Model: viewModel, Prefix: Prefix));
        }

        protected override DriverResult Editor(CustomerPart part, IUpdateModel updater, dynamic shapeHelper) {
            var viewModel = new CustomerViewModel();
            if(updater.TryUpdateModel(viewModel, Prefix, null, null)) {
                part.FirstName = viewModel.FirstName.TrimSafe();
                part.LastName = viewModel.LastName.TrimSafe();
                AddressViewModel.Map(viewModel.ShippingAddress, part.ShippingAddress, _countryRepository);
                AddressViewModel.Map(viewModel.BillingAddress, part.BillingAddress, _countryRepository);
            }
            
            return Editor(part, shapeHelper);
        }
    }
}